﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Common.QueryBuilder;

namespace System.Data.SQLite.QueryBuilder
{
    public class SQLiteQuerySelect : DbQuerySelect
    {
        private int _LimitOffset = -1;
        private int _LimitCount = -1;

        public SQLiteQuerySelect Limit(int rowCount)
        {
            if (rowCount < 0)
                throw new ArgumentException(String.Concat("Limit for Row Count cannot be smaller than 0 (value: ", rowCount, ")"));
            this._LimitOffset = rowCount;
            return this;
        }
        public SQLiteQuerySelect Limit(int offset, int rowCount)
        {
            if (rowCount < 0 || offset < 0)
                throw new ArgumentException(String.Concat(
                    "Limit for Row Count cannot be smaller than 0 (value: ", rowCount, ")", Environment.NewLine,
                    ", or Limit for Offset cannot be smaller than 0 (value: ", offset, ")"));
            this._LimitOffset = offset;
            this._LimitCount = rowCount;
            return this;
        }

        public SQLiteQuerySelect()
            : base()
        {
        }

        public SQLiteQuerySelect(String Table)
            : base(Table)
        {
        }

        public override string ToString()
        {
            String envNewLine = String.Concat(Environment.NewLine, "\t");
            String joins = this.Joins.Count > 0 ? String.Concat(String.Join(Environment.NewLine, this.Joins), Environment.NewLine) : String.Empty;
            String limit = String.Empty;
            if (this._LimitCount >= 0)
            {
                limit = String.Concat(" LIMIT ", (this._LimitOffset >= 0 ? String.Concat(this._LimitOffset, ", ") : String.Empty), this._LimitCount);
            }
            return String.Concat(
                "SELECT", String.Concat(Environment.NewLine, "\t "),
                    String.Join(String.Concat(Environment.NewLine, "\t,"), this.Columns), Environment.NewLine,
                "FROM ", this.TableName, Environment.NewLine,
                joins,
                this.GroupBy, Environment.NewLine,
                this.OrderBy, Environment.NewLine,
                limit);
        }
    }
}
